<template>
  <div class="modules-page">
    <div class="page-header">
      <h1>Module Management</h1>
      <el-button type="primary" @click="showCreateDialog = true">
        <el-icon><Plus /></el-icon>
        Add Module
      </el-button>
    </div>
    
    <el-card>
      <el-table
        v-loading="loading"
        :data="modules"
        style="width: 100%"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="name" label="Name" />
        <el-table-column prop="description" label="Description" />
        <el-table-column prop="icon" label="Icon" width="80">
          <template #default="{ row }">
            <el-icon v-if="row.icon">
              <component :is="row.icon" />
            </el-icon>
          </template>
        </el-table-column>
        <el-table-column prop="route" label="Route" />
        <el-table-column prop="sortOrder" label="Sort Order" width="100" />
        <el-table-column label="Status" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isActive ? 'success' : 'danger'">
              {{ row.isActive ? 'Active' : 'Inactive' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="Actions" width="150">
          <template #default="{ row }">
            <el-button size="small" @click="editModule(row)">
              <el-icon><Edit /></el-icon>
            </el-button>
            <el-button size="small" type="danger" @click="deleteModule(row)">
              <el-icon><Delete /></el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- Create/Edit Module Dialog -->
    <el-dialog
      v-model="showCreateDialog"
      :title="editingModule ? 'Edit Module' : 'Create Module'"
      width="500px"
    >
      <el-form
        ref="moduleFormRef"
        :model="moduleForm"
        :rules="moduleRules"
        label-width="120px"
      >
        <el-form-item label="Name" prop="name">
          <el-input v-model="moduleForm.name" />
        </el-form-item>
        
        <el-form-item label="Description">
          <el-input v-model="moduleForm.description" type="textarea" />
        </el-form-item>
        
        <el-form-item label="Icon">
          <el-input v-model="moduleForm.icon" placeholder="e.g., Dashboard, User, etc." />
        </el-form-item>
        
        <el-form-item label="Route">
          <el-input v-model="moduleForm.route" placeholder="e.g., /dashboard" />
        </el-form-item>
        
        <el-form-item label="Parent Module">
          <el-select v-model="moduleForm.parentId" clearable style="width: 100%">
            <el-option
              v-for="module in parentModules"
              :key="module.id"
              :label="module.name"
              :value="module.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="Sort Order">
          <el-input-number v-model="moduleForm.sortOrder" :min="0" />
        </el-form-item>
        
        <el-form-item v-if="editingModule" label="Status">
          <el-switch
            v-model="moduleForm.isActive"
            active-text="Active"
            inactive-text="Inactive"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="cancelEdit">Cancel</el-button>
        <el-button type="primary" :loading="saving" @click="saveModule">
          {{ editingModule ? 'Update' : 'Create' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import api from '@/api'

interface Module {
  id: number
  name: string
  description?: string
  icon?: string
  route?: string
  parentId?: number
  sortOrder: number
  isActive: boolean
  createdAt: string
  children?: Module[]
}

const modules = ref<Module[]>([])
const loading = ref(false)
const saving = ref(false)
const showCreateDialog = ref(false)
const editingModule = ref<Module | null>(null)
const moduleFormRef = ref<FormInstance>()

const moduleForm = reactive({
  name: '',
  description: '',
  icon: '',
  route: '',
  parentId: undefined as number | undefined,
  sortOrder: 0,
  isActive: true
})

const moduleRules: FormRules = {
  name: [
    { required: true, message: 'Please input module name', trigger: 'blur' }
  ]
}

const parentModules = computed(() => {
  return modules.value.filter(module => !module.parentId)
})

const loadModules = async () => {
  loading.value = true
  try {
    const response = await api.get('/modules/tree')
    modules.value = response.data
  } catch (error) {
    ElMessage.error('Failed to load modules')
  } finally {
    loading.value = false
  }
}

const editModule = (module: Module) => {
  editingModule.value = module
  moduleForm.name = module.name
  moduleForm.description = module.description || ''
  moduleForm.icon = module.icon || ''
  moduleForm.route = module.route || ''
  moduleForm.parentId = module.parentId
  moduleForm.sortOrder = module.sortOrder
  moduleForm.isActive = module.isActive
  showCreateDialog.value = true
}

const deleteModule = async (module: Module) => {
  try {
    await ElMessageBox.confirm(
      `Are you sure you want to delete module "${module.name}"?`,
      'Confirm Delete',
      {
        confirmButtonText: 'Delete',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }
    )
    
    await api.delete(`/modules/${module.id}`)
    ElMessage.success('Module deleted successfully')
    loadModules()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('Failed to delete module')
    }
  }
}

const saveModule = async () => {
  if (!moduleFormRef.value) return
  
  await moduleFormRef.value.validate(async (valid) => {
    if (valid) {
      saving.value = true
      try {
        if (editingModule.value) {
          await api.put(`/modules/${editingModule.value.id}`, moduleForm)
          ElMessage.success('Module updated successfully')
        } else {
          await api.post('/modules', moduleForm)
          ElMessage.success('Module created successfully')
        }
        
        showCreateDialog.value = false
        loadModules()
        resetForm()
      } catch (error) {
        ElMessage.error(editingModule.value ? 'Failed to update module' : 'Failed to create module')
      } finally {
        saving.value = false
      }
    }
  })
}

const cancelEdit = () => {
  showCreateDialog.value = false
  resetForm()
}

const resetForm = () => {
  editingModule.value = null
  Object.assign(moduleForm, {
    name: '',
    description: '',
    icon: '',
    route: '',
    parentId: undefined,
    sortOrder: 0,
    isActive: true
  })
  moduleFormRef.value?.resetFields()
}

onMounted(() => {
  loadModules()
})
</script>

<style scoped>
.modules-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}
</style>
